<?php
namespace common\core;

use common\core\base\BaseModule;

/**
 * Backend base module Class
 * 
 * @author Xuegui Yuan <yuanxuegui@163.com>
 */
class BackendModule extends BaseModule
{

    /**
     *
     * @var string
     */
    public $defaultRoute;

    /**
     *
     * @var array
     * @see [[items]]
     */
    private $_menus = [];

    /**
     *
     * @var array
     * @see [[items]]
     */
    public $menuItems = [];

    /**
     *
     * @var array
     * @see [[items]]
     */
    public $normalizeMenus;

    /**
     * Nav bar items
     *
     * @var array
     */
    public $navbar;

    /**
     * @inheritdoc
     */
    public function init()
    {
        parent::init();
    }

    /**
     * Get avalible menu.
     *
     * @return array
     */
    public function getMenus()
    {
        if ($this->normalizeMenus === null) {
            $mid = '/' . $this->getUniqueId() . '/';
            // resolve core menus
            $this->normalizeMenus = [];
            foreach ($this->menuItems as $id => $lable) {
                $this->normalizeMenus[$id] = [
                    'label' => $lable,
                    'url' => [
                        $mid . $id
                    ],
                    'icon' => '<i class="fa fa-angle-double-right"></i>'
                ];
            }
            foreach (array_keys($this->controllerMap) as $id) {
                $this->normalizeMenus[$id] = [
                    'label' => $lable,
                    'url' => [
                        $mid . $id
                    ],
                    'icon' => '<i class="fa fa-angle-double-right"></i>'
                ];
            }
            
            // user configure menus
            foreach ($this->menus as $id => $value) {
                if (empty($value)) {
                    unset($this->normalizeMenus[$id]);
                } else {
                    if (is_string($value)) {
                        $value = [
                            'label' => $value
                        ];
                    }
                    $this->normalizeMenus[$id] = isset($this->normalizeMenus[$id]) ? array_merge($this->normalizeMenus[$id], $value) : $value;
                    if (! isset($this->normalizeMenus[$id]['url'])) {
                        $this->normalizeMenus[$id]['url'] = [
                            $mid . $id
                        ];
                    }
                }
            }
        }
        return $this->normalizeMenus;
    }

    /**
     * Set or add avalible menu.
     *
     * @param array $menus            
     */
    public function setMenus($menus)
    {
        $this->menus = array_merge($this->menus, $menus);
        $this->normalizeMenus = null;
    }
}